package cn.edu.ncu.housinghub.interceptor;

import cn.edu.ncu.housinghub.constant.ErrorCodeConstant;
import cn.edu.ncu.housinghub.constant.SystemConstant;
import cn.edu.ncu.housinghub.entity.user.User;
import cn.edu.ncu.housinghub.vo.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Set;

@Component
public class AgentRoleCheckInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 拦截所有的中介请求（agent-rental/**） 验证是否角色类型为中介-4
        String requestURI = request.getRequestURI();
        if (requestURI.startsWith("/agent-rental")) {
            // 获取请求头中的token
            String token = request.getHeader("info");
            // 从Redis中查询token对应的用户信息
            Set<String> keys = redisTemplate.keys(SystemConstant.REDIS_TOKEN_PREFIX_USER.getStringValue() + "*:" + token);
            String key = keys.iterator().next();
            User user = (User) redisTemplate.opsForValue().get(key);
            // 如果用户类型不为中介
            if (user.getRole()!=SystemConstant.ROLE_AGENT.getIntegerValue()) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write(objectMapper.writeValueAsString(
                        Result.error(ErrorCodeConstant.Agent_INFO_NOT_MATCH.getCode(), ErrorCodeConstant.Agent_INFO_NOT_MATCH.getMessage())
                ));
            }
            return false;
        }
        return true;

    }
}
